const Food = require("../models/food");
const FoodUseNum = require("../models/foodusenum");
const collectServices = require("../services/collectService");
const sequelize = require("../config/sequelize");
const { changekeyWord } = require("../utils/changeKeyword");
const { Op } = require("sequelize");

// 获取食物分类
exports.getFoodcate = async function () {
  let foodcate = await Food.findAll({
    attributes: [
      [sequelize.fn("DISTINCT", sequelize.col("foodcate")), "foodcate"],
    ],
  });

  return foodcate;
};
// 获得分类下的食物
exports.getFood = async function (foodcate, userId) {
  const foodArr = await Food.findAll({
    where: { foodcate: foodcate },
    attributes: [
      "id",
      "name",
      "img",
      "heat_cal",
      "热量(大卡)",
      "碳水化合物(克)",
      "脂肪(克)",
      "蛋白质(克)",
    ],
  });
  for (let item of foodArr) {
    const foodId = item.id;
    item.dataValues.isCollect = await collectServices.isCollect(
      userId,
      foodId,
      "food"
    );
  }
  return foodArr;
};
// 获得食物的详情
exports.getFoodDetail = async function (foodId,userId) {
  const food = await Food.findOne({
    where: { id: foodId },
    attributes: [
      "id",
      "foodcate",
      "name",
      "img",
      "alias",
      "heat_cal",
      "热量(大卡)",
    ],
  });
  const nutritions = await Food.findOne({
    where: { id: foodId },
    attributes: ["碳水化合物(克)", "脂肪(克)", "蛋白质(克)"],
  });
  const elements = await Food.findOne({
    where: { id: foodId },
    attributes: {
      exclude: [
        "id",
        "foodcate",
        "name",
        "img",
        "alias",
        "heat_cal",
        "热量(大卡)",
      ],
    },
  });
  food.dataValues.elements = elements;
  food.dataValues.nutritions = nutritions;
  food.dataValues.isCollect = await collectServices.isCollect(userId,foodId,'food');
  return food;
};
// 搜索食物
exports.search = async function (value) {
  const searchKey = changekeyWord(value);
  return Food.findAll({
    where: {
      name: {
        [Op.regexp]: searchKey,
      },
    },
    attributes: ["id", "name", "img", "heat_cal"],
  });
};
// 获取常用和收藏食物
exports.getOftenAndCollect = async function (userId) {
  const oftenUseArr = await FoodUseNum.findAll({
    where: { userId },
    attributes: ["id", "num"],
    include: {
      model: Food,
      attributes: [
        "id",
        "img",
        "name",
        "heat_cal",
        "热量(大卡)",
        "碳水化合物(克)",
        "脂肪(克)",
        "蛋白质(克)",
      ],
      as: "food",
    },
    order: [["num", "DESC"]],
  });
  for (item of oftenUseArr) {
    const foodId = item.dataValues.food.id;
    item.dataValues.food.dataValues.isCollect = await collectServices.isCollect(
      userId,
      foodId,
      "food"
    );
  }
  const collectArr = await collectServices.collectFood(userId);
  collectArr.forEach((item) => {
    item.dataValues.food.dataValues.isCollect = true;
  });
  return {
    oftenUseArr,
    collectArr,
  };
};
